﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Reflection;
using hessiancsharp.client;
using xfsale.domain;
using xfsale.packet;
using xfsale.web.service;

namespace xfsale.lib
{
    public static class App
    {
        private static List<SysMenuItem> _menuItems;
        private static Hashtable _dictItems;
        private static Global _global = new Global();
        private static Customer _customer = new Customer();

        private static string _serviceUrl = ConfigurationManager.AppSettings["ServiceUrl"];
        private static CHessianProxyFactory _serviceFactory = new CHessianProxyFactory();

        public static List<SysMenuItem> MenuItems
        {
            get { return _menuItems; }
        }

        public static Hashtable DictItems
        {
            get { return _dictItems; }
        }

        public static Global Global
        {
            get { return _global; }
        }

        public static Customer Customer
        {
            get { return _customer; }
        }

        public static void Init()
        {
            try
            {
                Log.LogTo = Convert.ToInt32(ConfigurationSettings.AppSettings["LogTo"]);
                Log.LogLevel = Convert.ToInt32(ConfigurationSettings.AppSettings["LogLevel"]);
                Log.LogFile = ConfigurationSettings.AppSettings["LogFile"];
                Log.LogReset = ConfigurationSettings.AppSettings["LogReset"].ToUpper().Equals("Y");

            }
            catch
            {
                Log.LogTo = Log.LOGTO_FILE;
                Log.LogLevel = Log.LOGLVL_DEBUG;
                Log.LogFile = "Runtime.log";

                Log.LogThrowError("读取日志配置失败");
            }

            try
            {
                if (Log.LogReset)
                {
                    File.Delete(Log.LogFile);
                }
            }
            catch
            {
                Log.LogThrowError("删除日志文件失败");
            }

            Log.LogDebug("开始初始化客户端");

            Log.LogDebug("初始化菜单信息");
            _InitMenu();

            Log.LogDebug("初始化字典信息");
            _InitDict();

            Log.LogDebug("初始化全局信息");
            _InitGlobal();

            _InitCustomer();

            Log.LogDebug("结束初始化客户端");
        }

        public static void Dispose()
        {
            Log.LogDebug("开始释放客户端");

            _DisposeCustomer();

            Log.LogDebug("释放全局信息");
            _DisposeOperator();

            Log.LogDebug("释放字典信息");
            _DisposeDict();

            Log.LogDebug("释放菜单信息");
            _DisposeMenu();

            Log.LogDebug("结束释放客户端");
        }

        public static object CallService(string service, string method, object request)
        {
            object response = null;

            switch (service.ToUpper())
            {
                case "ORDERSERVICE":
                    response = CallOrderService(method, request);
                    break;

                case "SYSTEMSERVICE":
                    response = CallInfoService(method, request);
                    break;

                case "USERSERVICE":
                    response = CallUserService(method, request);
                    break;

                default:
                    return null;
            }

            return response;
        }

        public static object CallOrderService(string method, object request)
        {
            OrderService service = null;
            object response = null;

            Log.LogRequest(request);

            try
            {
                string url = _serviceUrl + "/order";
                service = (OrderService)_serviceFactory.Create(typeof(OrderService), url);
                MethodInfo mi = service.GetType().GetMethod(method);
                if (mi == null)
                {
                    throw new Error("OrderService不存在{0}方法", method);
                }

                response = mi.Invoke(service, new object[] { request });                
            }
            catch (Exception ex)
            {
                service = null;
                response = null;
                Log.LogThrowError("调用OrderService.{0}失败. {1}", method, ex.Message);
            }

            Log.LogResponse(response);

            return response;
        }

        public static object CallInfoService(string method, object request)
        {
            InfoService service = null;
            object response = null;

            Log.LogRequest(request);

            try
            {
                string url = _serviceUrl + "/info";
                service = (InfoService)_serviceFactory.Create(typeof(InfoService), url);
                response = service.GetType().GetMethod(method).Invoke(service, new object[] { request });
            }
            catch (Exception ex)
            {
                service = null;
                response = null;
                Log.LogThrowError("调用InfoService.{0}失败. {1}", method, ex.Message);
            }

            Log.LogResponse(response);

            return response;
        }

        public static object CallUserService(string method, object request)
        {
            UserService service = null;
            object response = null;

            Log.LogRequest(request);

            try
            {
                string url = _serviceUrl + "/user";
                service = (UserService)_serviceFactory.Create(typeof(UserService), url);
                response = service.GetType().GetMethod(method).Invoke(service, new object[] { request });
            }
            catch (Exception ex)
            {
                service = null;
                response = null;
                Log.LogThrowError("调用UserService.{0}失败. {1}", method, ex.Message);
            }

            Log.LogResponse(response);

            return response;
        }

        private static void _InitMenu()
        {
            SysMenuRequest request = new SysMenuRequest();
            SysMenuResponse response = (SysMenuResponse)CallInfoService("getSystemMenu", request);
            _menuItems = response.menuItems;
        }

        private static void _DisposeMenu()
        {
            if (_menuItems != null)
            {
                _menuItems.Clear();
                _menuItems = null;
            }
        }

        private static void _InitDict()
        {
            SysDictRequest request = new SysDictRequest();
            SysDictResponse response = (SysDictResponse)CallInfoService("getSystemDict", request);
            _dictItems = response.dictItems;
        }

        private static void _DisposeDict()
        {
            if (_dictItems != null)
            {
                _dictItems.Clear();
                _dictItems = null;
            }
        }

        private static void _InitGlobal()
        {
            SysParamRequest request = new SysParamRequest();
            SysParamResponse response = (SysParamResponse)CallInfoService("getSystemParam", request);
            _global.SysStatus = response.status;
            _global.SysWorkDay = response.workDay;
            _global.SysNextWorkDay = response.nextWorkDay;
            _global.SysVersion = response.version;
            _global.LogLevel = response.logLevel;
            _global.LogTo = response.logTo;
            _global.LogFile = response.logFile;
            _global.DistributorCode = response.distributorCode;
            _global.RegionCode = ConfigurationManager.AppSettings["RegionCode"];
            _global.BranchCode = ConfigurationManager.AppSettings["BranchCode"];
            _global.NetCode = ConfigurationManager.AppSettings["NetCode"];
        }

        private static void _DisposeOperator()
        {
            if (_global != null)
            {
                _global = null;
            }
        }

        private static void _InitCustomer()
        {
            _customer.Identified = false;
            _customer.TransAccountID = null;
            _customer.CustAccountID = null;
            _customer.CustName = null;
            _customer.CustNameAbbr = null;
            _customer.CustType = null;
            _customer.Nationality = null;
            _customer.CertType = null;
            _customer.CertNo = null;
        }

        public static void ResetCustomer()
        {
            _InitCustomer();
        }

        private static void _DisposeCustomer()
        {
            if (_customer != null)
            {
                _customer = null;
            }
        }
    }
}
